package top.xzhanyao.scaffold.compent.custom.log.log;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;

import java.lang.reflect.Method;

@Slf4j
@Aspect
public class MethodLogAspect {

    @Pointcut("@annotation(top.xzhanyao.scaffold.compent.custom.log.annotation.MethodExecuteLog)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object log(ProceedingJoinPoint point) {
        Object result = null;
        if (point instanceof MethodInvocationProceedingJoinPoint) {
            long start = System.currentTimeMillis();
            MethodInvocationProceedingJoinPoint methodPoint = (MethodInvocationProceedingJoinPoint) point;
            MethodSignature signature = (MethodSignature) methodPoint.getSignature();
            Method method = signature.getMethod();
            try {
                result = methodPoint.proceed();
            } catch (Throwable throwable) {
                log.error(ExceptionUtils.getStackTrace(throwable));
            } finally {
                long end = System.currentTimeMillis();
                log.info("Method log from aspect:{}-{}(), time cost:{} ms",
                        method.getDeclaringClass().getCanonicalName(), method.getName(), (end - start));
            }
        }
        return result;
    }

}
